package vista;

import java.awt.Choice;
import java.awt.GridBagLayout;
import java.awt.Rectangle;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;

//import ar.uba.fi.algo3.ejemplos.pelotas.controlador.EjemploPelotas;
//import ar.uba.fi.algo3.ejemplos.pelotas.controlador.ObservadorDeChoques;
import ar.uba.fi.algo3.titiritero.vista.Panel;
//import javax.swing.JLabel;

import persistencia.Administrador;
import persistencia.XMLUtils;

import modelo.Escenario;
import modelo.Nivel;

import controlador.Juego;
import controlador.ObservadorDeChoques;

import java.awt.GridBagConstraints;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class VentanaAplicacion extends JFrame implements ObservadorDeChoques {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JToolBar jJToolBarBar = null;
	private JMenuItem jMenuItem = null;
	private JMenuItem jMenuItem1 = null;
	private JMenuItem jMenuItem2 = null;
	private JMenuItem jMenuItem3 = null;
	private Panel panel = null;
	private Juego ejemplo = null;
	private JPanel jPanelEstado = null;
	private Nivel nivel = null;
	private Choice niveles;
	private boolean finalizado = false;
	private String pathNiveles = "/res/xml/";

	/**
	 * This method initializes jJToolBarBar
	 * 
	 * @return javax.swing.JToolBar
	 */
	private JToolBar getJJToolBarBar() {
		if (jJToolBarBar == null) {
			jJToolBarBar = new JToolBar();
			jJToolBarBar.setBounds(new Rectangle(0, 0, 372, 33));
			jJToolBarBar.add(getJMenuItem());
			jJToolBarBar.add(getJMenuItem1());
			jJToolBarBar.add(getJMenuItem2());
			jJToolBarBar.add(getJMenuItem3());
		}
		return jJToolBarBar;
	}

	private Choice getListaNiveles() throws URISyntaxException {
		URL u = this.getClass().getResource(pathNiveles);
		File f = new File(u.toURI());
		String[] lista = f.list();
		Choice choice = new Choice();
		for (int i = 0; i < lista.length; i++)
			choice.add(lista[i]);
		return choice;
	}

	/**
	 * This method initializes jMenuItem
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getJMenuItem() {
		if (jMenuItem == null) {
			jMenuItem = new JMenuItem();
			jMenuItem.setText("Comenzar");
			jMenuItem.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					System.out.println("actionPerformed()"); // TODO
																// Auto-generated
																// Event stub
																// actionPerformed()
				}
			});
			jMenuItem.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					comenzar();
				}
			});
		}
		return jMenuItem;
	}

	private void comenzar() {
		System.out.println("actionPerformed()");
		System.out.println("Comenzar VentanaAplicacion");

		if (this.finalizado)
			return;
		if (this.nivel == null) {
			try {
				String pathNivel;
				try {
					pathNivel = this.getClass().getResource(pathNiveles)
							.toURI().getPath()
							+ this.niveles.getSelectedItem();
					System.out.println("Intento abrir nivel " + pathNivel);
					nivel = (Nivel) XMLUtils.objectFromXMLFile(pathNivel);
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.exit(1);
			}
		}

		if (this.ejemplo == null)
			this.ejemplo = new Juego(getSuperficieDeDibujo(), nivel);
		this.ejemplo.agregarObservadorDeChoques(this);
		this.ejemplo.comenzar();
	}

	private void detener() {
		this.ejemplo.detener();
	}

	/**
	 * This method initializes jMenuItem1
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getJMenuItem1() {
		if (jMenuItem1 == null) {
			jMenuItem1 = new JMenuItem();
			jMenuItem1.setText("Detener");
			jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					System.out.println("actionPerformed()"); // TODO
																// Auto-generated
																// Event stub
																// actionPerformed()
					detener();
				}
			});
		}
		return jMenuItem1;
	}

	private JMenuItem getJMenuItem2() {
		if (jMenuItem2 == null) {
			jMenuItem2 = new JMenuItem();
			jMenuItem2.setText("Cargar");
			jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					System.out.println("actionPerformed()"); // TODO
																// Auto-generated
																// Event stub
																// actionPerformed()
					final JFileChooser fc = new JFileChooser();
					int returnVal = fc.showOpenDialog(VentanaAplicacion.this);
					if (returnVal == JFileChooser.APPROVE_OPTION) {
						File file = fc.getSelectedFile();
						cargar(file.getAbsolutePath());

					} else {
						System.out.println("cancel");
					}
				}
			});
		}
		return jMenuItem2;
	}

	private void cargar(String path) {
		if (this.ejemplo != null)
			this.detener();
		this.nivel = Administrador.cargarEstado(path);
		this.ejemplo = null;
		this.comenzar();
	}

	private JMenuItem getJMenuItem3() {
		if (jMenuItem3 == null) {
			jMenuItem3 = new JMenuItem();
			jMenuItem3.setText("Guardar");
			jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					System.out.println("actionPerformed()"); // TODO
																// Auto-generated
																// Event stub
																// actionPerformed()
					final JFileChooser fc = new JFileChooser();
					int returnVal = fc.showSaveDialog(VentanaAplicacion.this);
					if (returnVal == JFileChooser.APPROVE_OPTION) {
						File file = fc.getSelectedFile();
						System.out.println(file.getAbsolutePath());
						detener();
						guardar(file.getAbsolutePath());
						comenzar();
					} else {
						System.out.println("cancel");
					}
				}
			});
		}
		return jMenuItem3;
	}

	private void guardar(String path) {
		Administrador.guardarEstado(this.ejemplo.getNivel(), path);
	}

	/**
	 * This method initializes jPanel
	 * 
	 * @return javax.swing.JPanel
	 */
	private Panel getSuperficieDeDibujo() {
		int maxX = Escenario.getInstance().getXMax().intValue();
		int maxY = Escenario.getInstance().getYMax().intValue();
		if (panel == null) {
			panel = new Panel(200, 200);
			panel.setLayout(new GridBagLayout());
			panel.setBounds(new Rectangle(162, 38, maxX, maxY));
		}
		return panel;
	}

	/**
	 * This method initializes jPanelEstado
	 * 
	 * @return javax.swing.JPanel
	 * @throws URISyntaxException
	 */
	private JPanel getJPanelEstado() throws URISyntaxException {
		if (jPanelEstado == null) {
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.gridx = 1;
			gridBagConstraints1.gridy = 0;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 0;
			gridBagConstraints.gridy = 0;
			jPanelEstado = new JPanel();
			jPanelEstado.setLayout(new GridBagLayout());
			jPanelEstado.setBounds(new Rectangle(8, 41, 149, 194));
			this.niveles = this.getListaNiveles();
			jPanelEstado.add(this.niveles);
		}
		return jPanelEstado;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				VentanaAplicacion thisClass = new VentanaAplicacion();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}

	/**
	 * This is the default constructor
	 */
	public VentanaAplicacion() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(400, 200);
		try {
			this.setContentPane(getJContentPane());
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		this.setTitle("Menu Principal");
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
				System.out.println("windowClosing()"); // TODO Auto-generated
														// Event stub
														// windowClosing()
				System.exit(NORMAL);
			}
		});
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 * @throws URISyntaxException
	 */
	private JPanel getJContentPane() throws URISyntaxException {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(getJJToolBarBar(), null);
			jContentPane.add(getSuperficieDeDibujo(), null);
			jContentPane.add(getJPanelEstado(), null);
		}
		return jContentPane;
	}

	@Override
	public void huboChoques() {
		this.detener();
		this.finalizado = true;
	}

} // @jve:decl-index=0:visual-constraint="10,10"
